import { appConfigSetting } from '@/settings/appConfigSetting';
// @ts-ignore
import { createI18n, I18nOptions } from 'vue-i18n';
import { useAppSettingStoreWithOut } from '@/store/module/useAppSettingStore';
import { App } from 'vue';
import { setHtmlLanguage } from '@/locales/useLocale';

const { fallback } = appConfigSetting.configLocal;

export const getKeyByLower = (key: string): string => {
  return key.toLowerCase();
};

export let i18n: ReturnType<typeof createI18n>;
export const createI18nOptions = async (): Promise<I18nOptions> => {
  const appSettingStore = useAppSettingStoreWithOut();
  const locale = appSettingStore.getLocale;
  setHtmlLanguage(locale);
  const defaultLocal = await import(`./lang/${locale}.ts`);
  const message = defaultLocal.default;
  const messages = {
    [locale]: message,
  };
  return {
    legacy: true,
    locale,
    fallbackLocale: fallback,
    messages,
  } as I18nOptions;
};

export const setupLocales = async (app: App) => {
  const options = await createI18nOptions();
  i18n = createI18n(options as I18nOptions);
  app.use(i18n);
};
